<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\ProductType;
use App\Enums\RightsType;
use App\Exports\DeliveryExport;
use App\Http\Controllers\Controller;
use App\Jobs\DownloadsJob;
use App\Models\AgentUser;
use App\Models\Download;
use App\Models\Product;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class RightsController extends Controller
{
    /** 查询有实物权益的商品 */
    public function listProductsWithEntityRights()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $query = Product::query()->where('rights_type', RightsType::ENTITY)
            ->where('type', ProductType::ISSUE)
            ->where('agent_id', $user->agent_id)
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 导出指定商品的购买人 */
    public function exportProductBuyers()
    {
        $product = Product::query()->find(request()->id ?: 0);
        if (!$product) {
            throw new AdminException('商品未找到');
        }
        if ($product->rights_type->isNot(RightsType::ENTITY)) {
            throw new AdminException('当前商品没有实物权益');
        }
        /** @var AgentUser $user */
        $user = auth()->user();

        $file = $product->name . '购买记录' . date('YmdHis') . uniqid() . '.xls';

        $download = Download::create([
            'agent_id' => $user->agent_id,
            'user_id' => $user->id,
            'name' => $file,
            'url' => 'storage/' . $file,
            'status' => 0,
            'model' => DeliveryExport::class,
            'request' => json_encode(request()->all()),
        ]);

        dispatch(new DownloadsJob($download));
    }
}
